package pers.zxk.jlytnews.servlet;

import net.sf.json.JSONArray;
import pers.zxk.jlytnews.dao.FoodDao;
import pers.zxk.jlytnews.dao.impl.FoodDaoImpl;
import pers.zxk.jlytnews.entity.Food;
import pers.zxk.jlytnews.entity.FoodWithType;
import pers.zxk.jlytnews.manager.UserStateManager;
import pers.zxk.jlytnews.util.CommonUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;


@MultipartConfig
public class FoodServlet extends HttpServlet {
    private FoodDao mFoodDao = new FoodDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取能够与“url-pattern”中匹配的路径
        String method = req.getServletPath();

        //(此时处理的请求是查询 query.do)
        System.out.println("request.getServletPath()获取的值为: " + method);//输出 /query.do

        //2.通过字符串截取，把方法名 query 截取出来
        int i = method.lastIndexOf("/");
        method = method.substring(i + 1, method.length());

        System.out.println("截取后的值为： " + method);

        Method m = null;
        try {
            //3.获取当前类中名字为 method 的方法
            m = this.getClass().getDeclaredMethod(method,
                    HttpServletRequest.class, HttpServletResponse.class);

            //4.调用 method 方法
            m.setAccessible(true);
            m.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addFood(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //判断用户权限
        if(!UserStateManager.isAdmin(req)){
            CommonUtil.sendJsonData(resp, null, 1, "无权操作！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String name = req.getParameter("name");

        String path = "";
        Part part = req.getPart("image");
        if (part.getSubmittedFileName() != null) {//如果能拿到part中保存的图片名称，再保存图片
            path = CommonUtil.saveImage(part);//保存图片，返回图片路径
        }

        String type = req.getParameter("type");
        String description = req.getParameter("description");
        String remarks = req.getParameter("remarks");

        //添加数据并向客户端返回消息
        try {
            boolean isSuccess = mFoodDao.addFood(name, Integer.valueOf(type), path, description, remarks);
            if (isSuccess) {
                CommonUtil.sendJsonData(resp, "添加成功", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, "添加失败", 1, "");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, "添加失败", 1, exception.getMessage());
        }
    }

    public void delFood(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //判断用户权限
        if(!UserStateManager.isAdmin(req)){
            CommonUtil.sendJsonData(resp, null, 1, "无权操作！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String id = req.getParameter("id");

        //删除数据并向客户端返回消息
        try {
            //删除图片
            Food food = mFoodDao.getFood(Integer.parseInt(id));
            String url = food.getImage();
            String realPath = CommonUtil.urlToPath(url);
            if (realPath != null) {
                new File(realPath).delete();
            }

            //删除记录
            boolean isDeleted = mFoodDao.delFood(Integer.parseInt(id));
            if (isDeleted) {
                CommonUtil.sendJsonData(resp, "删除成功", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, "删除失败", 1, "");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, "删除失败", 1, exception.getMessage());
        }
    }

    public void updateFood(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //判断用户权限
        if(!UserStateManager.isAdmin(req)){
            CommonUtil.sendJsonData(resp, null, 1, "无权操作！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        Part part = req.getPart("image");
        String path = CommonUtil.saveImage(part);//保存图片，返回图片路径
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String type = req.getParameter("type");
        String description = req.getParameter("description");
        String remarks = req.getParameter("remarks");

        //更新数据并向客户端返回消息
        try {
            //删除旧图片
            Food food = mFoodDao.getFood(Integer.parseInt(id));
            String oldPath = food.getImage();
            String realPath = CommonUtil.urlToPath(oldPath);
            if (realPath != null) {//旧图片存在
                if (!oldPath.equals(path)) {//旧图片和新图片不同
                    new File(realPath).delete();
                }
            }

            boolean isUpdated = mFoodDao.updateFood(Integer.parseInt(id), name, Integer.parseInt(type), path, description, remarks);
            if (isUpdated) {
                CommonUtil.sendJsonData(resp, "更新成功", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, "更新失败", 0, "");
            }

        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, "更新失败", 0, exception.getMessage());
        }
    }

    // 通过id获取菜品
    public void getFood(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String id = req.getParameter("id");

        //获取数据并发送给客户端
        try {
            Food food = mFoodDao.getFood(Integer.parseInt(id));
            if (food != null) {
                CommonUtil.sendJsonData(resp, food, 0, "");
            } else {
                CommonUtil.sendJsonData(resp, null, 1, "未找到数据");
            }
        } catch (Exception e) {
            CommonUtil.sendJsonData(resp, null, 1, e.getMessage());
        }
    }

    public void getAllFood(HttpServletRequest req, HttpServletResponse resp) {
        //从数据库获取数据
        try {
            List<Food> list = mFoodDao.getAllFood();
            //将数据转为json类型
            JSONArray jsonArray = JSONArray.fromObject(list);
            if (jsonArray != null) {
                CommonUtil.sendJsonData(resp, jsonArray, 0, "");
            } else {
                CommonUtil.sendJsonData(resp, null, 0, "未找到数据");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, null, 0, exception.getMessage());
        }
    }

    //通过类型获取菜品 炒菜、炖菜等
    public void getAllFoodWithType(HttpServletRequest req, HttpServletResponse resp) {
        //从数据库获取数据
        try {
            List<FoodWithType> list = mFoodDao.getAllFoodWithType();
            //将数据转为json类型
            JSONArray jsonArray = JSONArray.fromObject(list);
            if (jsonArray != null) {
                CommonUtil.sendJsonData(resp, jsonArray, 0, "");
            } else {
                CommonUtil.sendJsonData(resp, null, 0, "未找到数据");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, null, 0, exception.getMessage());
        }
    }

}
